package com.yjc.hire.auth.controller;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.yjc.bo.RegistLoginBO;
import com.yjc.hire.auth.VO.UsersVO;
import com.yjc.hire.auth.pojo.Users;
import com.yjc.hire.auth.service.UserService;
import com.yjc.hire.base.BaseInfoProperties;
import com.yjc.hire.grace.result.GraceJSONResult;
import com.yjc.hire.grace.result.ResponseStatusEnum;
import com.yjc.hire.mq.RabbitMqSMSConfig;
import com.yjc.hire.utils.IPUtil;
import com.yjc.hire.utils.JWTUtils;
import com.yjc.hire.utils.JsonUtils;
import com.yjc.mq.SMSContentQO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author jcyin
 * @since 2025/6/29
 * </p>
 */
@RestController
@Slf4j
@RequestMapping("passport")
public class PassPortController extends BaseInfoProperties {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;
    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("getSMSCode")
    public GraceJSONResult getSMSCode(String mobile,
                                      HttpServletRequest request) {
        log.info("发送的电话号码为 " + mobile);
        if (StringUtils.isBlank(mobile)){
            return GraceJSONResult.error();
        }
//        String code = (int)((Math.random() * 9 + 1) * 100000) + "";
        String code = "1234";
        SMSContentQO qo = new SMSContentQO(mobile, code);
//        //定义comfirm进行会调
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            @Override
//            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//
//            }
//        });
//        定义return会调函数
//        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
//            @Override
//            public void returnedMessage(ReturnedMessage returnedMessage) {
//                log.info("进入return");
//                log.info(returnedMessage.toString());
//            }
//        });
//        //消息处理的类对象对当时需要超时的ttl进行参数属性设置
//        MessagePostProcessor processor = new MessagePostProcessor() {
//            @Override
//            public Message postProcessMessage(Message message) throws AmqpException {
//                message.getMessageProperties().setExpiration(String.valueOf(TimeUnit.SECONDS.toSeconds(30)));
//                return message;
//            }
//        };
        rabbitTemplate.convertAndSend(RabbitMqSMSConfig.SMS_EXCHANGE,RabbitMqSMSConfig.ROUTING_KEY_SNS_SEND_LOGIN,
                Objects.requireNonNull(JsonUtils.objectToJson(qo)));

        //把验证码存到redis设置过期时间为30分钟
//       redisTemplate.opsForValue().set(MOBILE_SMSCODE + ":" + mobile, code,30 * 60, TimeUnit.SECONDS);
        //进行限制
        String requestIp = IPUtil.getRequestIp(request);
        redisTemplate.opsForValue().setIfAbsent(MOBILE_SMSCODE + ":" + requestIp, mobile,60, TimeUnit.SECONDS);

        return GraceJSONResult.ok();
    }

    @PostMapping("login")
    public GraceJSONResult getSmsCode(@Valid @RequestBody RegistLoginBO bo,
                                      HttpServletRequest request) throws MethodArgumentNotValidException {
        String smsCode = bo.getSmsCode();
        String mobile = bo.getMobile();

        String code = redisTemplate.opsForValue().get(MOBILE_SMSCODE + ":" + mobile);
        if (StringUtils.isBlank(code) || !code.equals(smsCode)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }
        Users user = userService.queryMobileIsExist(mobile);
        if (user == null){
            user = userService.createUser(mobile);
        }
//
//        String uToken = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(REDIS_USER_TOKEN + ":" + user.getId(),uToken);
        String jwtToken = jwtUtils.createJWtWithPrefix(new Gson().toJson(user),Long.valueOf(1000),TOKEN_USER_PREFIX);
        //用户登录完成后删除登录短信验证码
        redisTemplate.delete(MOBILE_SMSCODE + ":" + mobile);
        UsersVO vo = new UsersVO();
        BeanUtils.copyProperties(user,vo);
        vo.setUserToken(jwtToken);
        return GraceJSONResult.ok(vo);

    }

    @PostMapping("logout")
    public GraceJSONResult logout(@RequestParam String userId,HttpServletRequest request) {
        redisTemplate.delete(REDIS_USER_TOKEN + ":" +userId);
        return GraceJSONResult.ok();
    }
}
